package com.yourenbang.lingyun.transaction.web.controller.fund;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.fund.AccountType;
import com.yourenbang.lingyun.core.base.controller.BaseController;
import com.yourenbang.lingyun.core.base.interceptor.ExcludeInterceptor;
import com.yourenbang.lingyun.core.message.Request;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.http.HttpClientUtil;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundBillMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.fund.*;
import com.yourenbang.lingyun.transaction.web.domain.vo.fund.AccountQueryGroupVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.fund.AccountQueryVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.fund.AllyHomePageVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.fund.MerAccountQueryGroupVO;
import com.yourenbang.lingyun.transaction.web.service.CommonService;
import com.yourenbang.lingyun.transaction.web.service.fund.AccountService;
import com.yourenbang.lingyun.transaction.web.service.fund.AccountSystemService;
import com.yourenbang.transaction.api.model.dto.TopupApplyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/transaction/fund/account")
public class AccountController extends BaseController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountSystemService accountSystemService;
    @Autowired
    private TransactionFundBillMapper transactionFundBillMapper;

    @Autowired
    private CommonService commonService;

    @ExcludeInterceptor
    @PostMapping(value = "/system/topup")
    public Result topupApply(@Validated @RequestBody Request<TopupApplyDTO> dtoRequest, BindingResult br) {

        if (br.hasErrors()) {
            return checkParamError(br);
        }
        KLog.info("[系统账户充值入参]:{}", dtoRequest);
        return accountSystemService.topupApply(dtoRequest.getData());
    }

    /**
     * 用户账户查询, 银小云没有用到
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/5006">火眼接口连接</a>
     */
    @PostMapping(value = "/query")
    public Result<AccountQueryVO> queryAccount(@Validated @RequestBody Request<AccountQueryDTO> dto, BindingResult br) {
        KLog.info("【用户账户查询】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.queryAccount(dto.getData());
    }

    /**
     * 盟友账户查询 V2版本，目前只支持银小云
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/14622">火眼接口连接</a>
     */
    @PostMapping(value = "/query/group/v2")
    public Result<AccountQueryGroupVO> queryAccountGroupV2(@Validated @RequestBody Request<AccountQueryDTO> dto, BindingResult br) {
        log.info("【盟友账户查询V2】入参:{}", JSONObject.toJSONString(dto));
        String httpPostRequest = "";
        String postUrl = "https://testapi.mugeyrb.com/transaction/fund/account/query/group/v2";
        if (commonService.isProd()) {
            postUrl = "http://172.17.187.6:8886/transaction/fund/account/query/group/v2";
        }
        try {
            httpPostRequest = HttpClientUtil.httpPostRequest(postUrl, JSONObject.toJSONString(dto));
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("盟友账户查询V2,出参：{}", httpPostRequest);
//        Map<String, T> resultMap = new HashMap<>();
//        Class<? extends AllyAwardBonusQueryVO> HashMap;
        HashMap<String,AccountQueryGroupVO> map = JSONObject.parseObject(httpPostRequest, HashMap.class);
        //result = JSONObject.parseObject(httpPostRequest,Map.class);
        return Result.builder().success(map.get("data"));
//        if (commonService.repeatSubmit("queryAccountGroupV2:" + dto.getUserId())) {
//            log.info("重复查询盟友账户查询V2版本,等待1秒:{}", dto.getUserId());
//
//            try {
//                Thread.sleep(1000l);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        Result result = verifyParam(br);
//        if (!result.isSuccess()) {
//            return result;
//        }
//        return accountService.queryAccountGroupV2(dto.getData());
    }

    /**
     * 查询盟友账户，新盟友账户页 中间部分
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/14623">火眼接口连接</a>
     */
    @PostMapping(value = "/query/ally/account/list")
    public Result<List<AllyAccountVO>> queryAllyAccountList(@Validated @RequestBody Request<AccountQueryDTO> dto, BindingResult br) {
        KLog.info("【查询盟友账户】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.queryAllyAccountList(dto.getData());
    }
    /**
     * 商户账户查询
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/6934"接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping(value = "/query/group/mer")
    public Result<MerAccountQueryGroupVO> queryMerAccountGroup(@Validated @RequestBody Request<MerAccountQueryDTO> dto, BindingResult br) {
        KLog.info("【商户账户查询】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.queryMerAccountGroup(dto.getData());
    }

    /**
     * 商户今日收益查询
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/13041"接口连接</a>
     */
    @PostMapping(value = "/query/mer/today/income")
    public Result<BigDecimal> queryMerTodayIncome(@Validated @RequestBody Request<MerAccountQueryDTO> dto, BindingResult br) {
        KLog.info("【商户今日收益查询】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        MerAccountQueryDTO merAccountQueryDTO = dto.getData();
        BigDecimal merTodayIncome = transactionFundBillMapper
                .getMerTodayIncome(merAccountQueryDTO.getPlatNo(),merAccountQueryDTO.getUserBaseId(), DateFormat.DATE_COMPACT.format(LocalDateTime.now()),
                        AccountType.getFullCode(AccountType.MER, merAccountQueryDTO.getPlatNo()));
        return Result.builder().success(merTodayIncome);
    }

    /**
     * 商户账户查询(快收查凌云)
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/6966"接口连接</a>
     */
    @PostMapping(value = "/query/group/mer/klks")
    public Result<MerAccountQueryGroupVO> queryMerAccountGroupFromKlks(@Validated @RequestBody Request<MerAccountQueryKlksDTO> dto, BindingResult br) {
        KLog.info("【商户账户查询(快收查凌云)】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.queryMerAccountGroupFromKlks(dto.getData());
    }

    /**
     * 快收用户账户查询
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/5014">火眼接口连接</a>
     */
    @PostMapping(value = "/query/all/klks")
    public Result<AccountQueryVO> queryAllKlks(@Validated @RequestBody Request<KlksAccountQueryDTO> dto, BindingResult br) {
        KLog.info("【用户账户查询】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.queryAllKlks(dto.getData());
    }

    /**
     * 快收用户所有账户查询转发
     */
    @ExcludeInterceptor
    @PostMapping(value = "/query/all/klks/forward")
    public Result<String> queryAllKlksForward(@RequestBody String param) {
        KLog.info("【用户所有账户查询(快收查凌云)】入参:{}", param);
        return accountService.queryAllKlksForward(param);
    }


    /**
     * 盟友首页收益
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/5350">火眼接口连接</a>
     */
    @PostMapping(value = "/all/home")
    public Result<AllyHomePageVO> allyHomePage(@Validated @RequestBody Request<AllyHomePageDTO> dto, BindingResult br) {
        KLog.info("【盟友首页收益】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.allyHomePage(dto.getData());
    }

    /**
     * 快收盟友首页收益
     * @see <a href="https://huoyan.kaolakuaishou.cn/project/97/interface/api/5358">火眼接口连接</a>
     */
    @ExcludeInterceptor
    @PostMapping(value = "/all/home/klks")
    public Result<AllyHomePageVO> allyHomePageFromKlks(@Validated @RequestBody Request<KlksAllyHomePageDTO> dto, BindingResult br) {
        KLog.info("【快收盟友首页收益】入参:{}", dto.toJSON());
        Result result = verifyParam(br);
        if (!result.isSuccess()) {
            return result;
        }
        return accountService.allyHomePageFromKlks(dto.getData());
    }

}